<template>
  <div class="Home" low-code>
    <!--使用draggable组件-->
    <div class="wrap">
      <!-- 侧边栏 -->
      <sidebar></sidebar>
      <!-- :class="{active: 'interface' == store.current.key}" -->
      <div v-if="store" class="main" @click="designInterface">
        <div class="operation" :class="[exchange?'front-desk':'background']">
          <div class="before-and-after">
            <div class="undo" @click="undo">
              <i class="el-icon-refresh-left"></i>
              <span>撤销</span>
            </div>
            <div class="restore" @click="restore">
              <i class="el-icon-refresh-right"></i>
              <span>恢复</span>
            </div>
          </div>

          <div class="import-and-export-previw-clear">



            <div class="preview" @click="designModel">
              <i :class="[exchange?'el-icon-sunny':'el-icon-moon']"></i>
              <span>{{exchange?'后台':'前台'}}</span>
            </div>

            <div class="import" @click="importJson">
              <i class="el-icon-download"></i>
              <span>导入</span>
            </div>

            <div class="export" @click="exportJson">
              <i class="el-icon-upload2"></i>
              <span>导出</span>
            </div>

            <div class="preview" @click="preview">
              <i class="el-icon-view"></i>
              <span>预览</span>
            </div>

            <div class="clear" @click="clearDesign">
              <i class="el-icon-delete"></i>
              <span>清空</span>
            </div>

            <!-- <div class="import" @click="cssControl">
              <i class="el-icon-present"></i>
              <span>样式</span>
            </div> -->

            <div class="preview" @click="saveTemplate">
              <i class="el-icon-lollipop"></i>
              <span>保存</span>
            </div>

            <div class="messagePool" >
              <span>{{messagePool.getSize()}}</span>
            </div>


          </div>

        </div>

        <div :class="['design-interface',store.className?store.className:'']">

          <design-area :exchange="exchange"></design-area>

        </div>

      </div>
      <div class="nature">
        <!-- 组件设置 -->
        <setting v-if="store" :store="store"></setting>
      </div>
    </div>

    <!-- 预览弹框 -->
    <el-dialog title="预览效果" append-to-body :close-on-click-modal="false" destroy-on-close :visible.sync="dialogVisible" fullscreen>
      <!-- 解析器 -->
      <preview-parse v-if="dialogVisible" :store="store"></preview-parse>

      <el-dialog width="45%" title="获取数据" :close-on-click-modal="false" :visible.sync="innerVisible" append-to-body>
        <editor v-model="exportData" @init="editorInit" :options="editorOptions" lang="json" theme="chrome" width="100%" height="350"></editor>
      </el-dialog>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="getFormData">获取数据</el-button>
      </span>
    </el-dialog>

    <!-- 导入JSON -->
    <el-dialog title="导出JSON" append-to-body :close-on-click-modal="false" :visible.sync="importJsonVisible" width="70%">
      <div>
        <editor v-model="importcontent" @init="editorInit" :options="editorOptions" lang="json" theme="chrome" width="100%" height="350"></editor>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="importJsonVisible = false">取 消</el-button>
        <el-button type="primary" @click="importSure">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 导出JSON -->
    <el-dialog title="导出JSON" append-to-body :close-on-click-modal="false" :visible.sync="editorVisible" width="70%">
      <div>
        <editor v-model="content" @init="editorInit" :options="editorOptions" lang="json" theme="chrome" width="100%" height="350"></editor>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editorVisible = false">取 消</el-button>
        <el-button type="primary" @click="editorVisible = false">确 定</el-button>
      </span>
    </el-dialog>

    <drawer title="自定义样式" :drawerShow.sync="cssVisible">

      <div slot="body">
        <editor v-model="cssText" @init="cssInit" :options="editorOptions" lang="scss" theme="chrome" width="100%" height="350"></editor>
        <div class="footer">
          <el-button @click="cssVisible=false">关闭</el-button>
          <el-button type="primary" @click="saveCss">保存</el-button>
        </div>
      </div>

    </drawer>

  </div>
</template>

<script>
  // eslint-disable-next-line no-unused-vars
  import { createStore,Store } from "@/low-code/utils/store.js"
  import { event } from "@/low-code/utils/event.js"
  // import { cache } from "@/low-code/utils/storage.js"
  import clone from 'clone'
  import Setting from "./setting/index.vue"
  import Sidebar from "./sidebar/index.vue"
  import PreviewParse from "./components/parse/index.vue"
  import Drawer from "@/low-code/components/drawer/"
  import designArea from "@/low-code/design-area/"


  export default {
    name: 'Home',
    provide () {
      return {
        model: 'design',//设计界面
        getStore: () => {
          return this.store
        },

        getPcStore:() => {
          return this.temPcStore
        },
        getMobileStore:() => {
          return this.temMobileStore
        },
        getImportEditor:() => {
          return this.importEditor
        }
      };
    },
    components: {
      designArea,
      Drawer,
      Setting,
      Sidebar,
      PreviewParse,
      editor: require('vue2-ace-editor'),
      // com:com.$options
    },
    data () {
      return {
        terminal: 'pc',
        temPcStore: null,
        temMobileStore: null,
        exchange: true,
        soo: "",
        store: null,
        cssVisible: false,
        dialogVisible: false,
        innerVisible: false,
        editorVisible: false,
        importJsonVisible: false,
        formParcel: ['sinput'],
        importcontent: "",
        content: "",
        cssText: '',
        editorOptions: {
          enableBasicAutocompletion: true, // 启用基本自动完成
          enableSnippets: true, // 启用代码段
          enableLiveAutocompletion: true, // 启用实时自动完成
          printMarginColumn: 30,
          displayIndentGuides: false, // 显示参考线
          enableEmmet: true, // 启用Emmet
          tabSize: 5, // 标签大小
          fontSize: 12, // 设置字号
          useWorker: true, // 使用辅助对象
          showPrintMargin: false, //去除编辑器里的竖线
          enableMultiselect: true, //     选中多处
          readOnly: false, // 是否只读
          showFoldWidgets: true, // 显示折叠部件
          fadeFoldWidgets: true, // 淡入折叠部件
          wrap: true //换行
        },
        exportData: "",
        messagePool: Store.messagePool
      };
    },
    methods: {
      saveCss () {
        this.store.cssText = this.cssText
        this.store.style.addNewStyle(this.store.cssText)
        // this.cssVisible = false
      },
      cssControl () {
        this.cssText = this.store.cssText
        this.cssVisible = true
      },
      designModel () {
        this.exchange = !this.exchange
        if (this.exchange == false) {
          this.store.designModel = 'background'
        } else {
          this.store.designModel = 'front-desk'
        }
      },
      saveTemplate () {

        if (this.terminal == 'mobile') {
          alert("移动端暂时不允许保存")
          return false
        }

        let store = {
          formId: this.store.formId,
          tableConfig: this.store.tableConfig,
          paramsDefine:this.store.paramsDefine,
          root: this.store.root,
          models: this.store.models,
          beginEvents: this.store.beginEvents,
          eventMap: this.store.eventMap,
          eventCollection: this.store.eventCollection,
          formDataSource: this.store.formDataSource,
          cssText: this.store.cssText,
          configuration:this.store.configuration,
          submitInterceptor:this.store.submitInterceptor
        }
        event.fire('saveTemplate', JSON.stringify(store))
      },
      editorInit: function () {
        require('brace/ext/language_tools') //language extension prerequsite...             
        require('brace/theme/chrome')
        require('brace/mode/javascript')    //language
        require('brace/snippets/javascript') //snippet
        require('brace/mode/json')    //language
        require('brace/snippets/json') //snippet

      },
      cssInit: function () {
        require('brace/ext/language_tools') //language extension prerequsite...             
        require('brace/theme/chrome')
        require('brace/mode/scss')    //language
        require('brace/snippets/scss') //snippet
      },
      getFormData () {
        /**
         * 获取表单数据
         */
        this.exportData = JSON.stringify(this.store.models, null, 2) 
        this.innerVisible = true
      },
      preview () {
        this.dialogVisible = true
        console.log('this.store', this.store)
      },
      designInterface () {
        this.store.current = {
          key: "interface"
        }
      },
      importJson () {
        this.importJsonVisible = true
      },
      importEditor (importcontent) {
        if (!importcontent) {
          return false
        }
        try {
          let store = createStore(JSON.parse(importcontent))
          this.store = store
          //添加监听 current事件
          this.store.eventCenter.on('current', (data) => {
            this.store.current = data;
          })

          this.importJsonVisible = false
        } catch (error) {
          console.log("error",error)
          this.$message('解析错误,请传入正确格式');
        }

      },
      importSure () {
        if (!this.importcontent) {
          return false
        }
        try {
          let store = createStore(JSON.parse(this.importcontent))
          this.store = store
          //添加监听 current事件
          this.store.eventCenter.on('current', (data) => {
            this.store.current = data;
          })

          this.importJsonVisible = false
        } catch (error) {
          console.log("error",error)
          this.$message('解析错误,请传入正确格式');
        }

      },
      exportJson () {
        let store = {
          formId: this.store.formId,
          tableConfig: this.store.tableConfig,
          params:this.store.params,
          paramsDefine:this.store.paramsDefine,
          root: this.store.root,
          models: this.store.models,
          beginEvents: this.store.beginEvents,
          eventMap: this.store.eventMap,
          eventCollection: this.store.eventCollection,
          formDataSource: this.store.formDataSource,
          cssText: this.store.cssText,
          configuration:this.store.configuration,
          submitInterceptor:this.store.submitInterceptor
        }
        this.content = JSON.stringify(store, null, 2)
        this.editorVisible = true
      },
      clearDesign () {
        this.store.root = {
          list: [],
          blackList: [],
          config: {
            labelWidth: 80,
            labelPosition: 'right',
            size: 'small'
          },
        }
        this.store.models = {}
        this.store.paramsDefine = []
        this.store.beginEvents = []
        this.store.eventMap = {}
        this.store.eventCollection = []
        this.store.formDataSource = {}
        this.store.componentsMap = {}
        this.store.cssText = ''
        this.store.configuration={}
        this.$handleStack.clear()
      },
      reFreshComponent (flag) {
        this[flag] = false;
        this.$nextTick(() => {
          this[flag] = true;
        });
      },
      undo () {
        let widgetForm = null
        if (this.$handleStack.getLastOperation() === 'push') {
          widgetForm = this.$handleStack.pop()
          this.$restoreHandleStack.push(widgetForm)
        }
        widgetForm = clone(this.$handleStack.pop())

        widgetForm ? (
          () => {
            this.store.root = widgetForm
          }
        )() : (
          this.store.root = {
            list: [],
            blackList: [],
            config: {
              labelWidth: 80,
              labelPosition: 'right',
              size: 'small'
            },
          }
        )
        this.$restoreHandleStack.push(widgetForm)
        this.store.current = {}
      },
      restore () {
        if (this.$restoreHandleStack.getLastOperation() === 'push') {
          widgetForm = this.$restoreHandleStack.pop()
          this.$handleStack.push(widgetForm)
        }
        let widgetForm = clone(this.$restoreHandleStack.pop())
        widgetForm && (() => {
          this.store.root = widgetForm
          this.$handleStack.push(widgetForm)
        })()
        this.store.current = {}
      },
    },
    mounted () {

      this.store = createStore({
        root: {
          list: [],
          blackList: [],
          config: {
            labelWidth: 80,
            labelPosition: 'right',
            size: 'small'
          },
        }
      })

      // this.messagePool.set('www',123)
      // console.log('messagePool',this.messagePool)
    },
    destroyed () {
      this.store.lifeCycle.destroyed()
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
.wrap {
  padding: 10px;
  display: flex;
}

.col {
  width: 40%;
  flex: 1;
  padding: 10px;
  border: solid 1px #eee;
  border-radius: 5px;
  float: left;
}

/* .col + .col {
  margin-left: 10px;
} */

.sidebar {
  width: 260px;
  height: calc(100vh - 80px);
  overflow-y: auto;
  flex-shrink: 0;
}
.main {
  flex: 1;
  border: 1px solid #cccccc;
  overflow: auto;
}


.nature {
  width: 280px;
  height: calc(100vh - 60px);
  overflow-y: auto;
  flex-shrink: 0;
}

.clearfix:after {
  /*伪元素是行内元素 正常浏览器清除浮动方法*/
  content: "";
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}
.clearfix {
  *zoom: 1; /*ie6清除浮动的方式 *号只有IE6-IE7执行，其他浏览器不执行*/
}

.header {
  line-height: 60px;
  border-bottom: 1px dashed #999;
}
.header .title {
  float: left;
  padding-left: 20px;
}
.header .preview,
.header .save,
.header .close,
.header .export,
.header .clear,
.header .undo,
.header .restore {
  float: right;
  margin-right: 20px;
}
.undo {
  color: red !important;
}
.restore {
  color: #2aa0fa !important;
}
.design-interface {
  overflow-y: auto;
  border: 1px dashed #999;
  height: calc(100vh - 100px);
}
.design-interface.active {
  outline: 2px solid #409eff;
  border: 1px solid #409eff;
}
.operation {
  display: flex;
  line-height: 38px;
  justify-content: space-between;
  .before-and-after {
    width: 150px;
  }
  .import-and-export-previw-clear {
    width: 400px;
    & > div {
      color: #2aa0fa !important;
    }
  }
  .before-and-after,
  .import-and-export-previw-clear {
    display: flex;
    justify-content: space-around;
    & > div {
      cursor: pointer;
      color: #cccccc;
      font-size: 13px;
      user-select: none;
    }
    i {
      margin-right: 8px;
    }
  }
}

.operation.background {
  background: black;
  .import-and-export-previw-clear {
    & > div {
      color: white !important;
    }
  }
  .before-and-after,
  .import-and-export-previw-clear {
    & > div {
      color: white;
    }
  }
}

/* fade-transform */
.fade-transform-leave-active {
  transition: all 0s;
}
.fade-transform-enter-active {
  transition: all 0.5s;
}

.fade-transform-enter {
  opacity: 0;
  transform: translateX(-30px);
}

.fade-transform-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

.drawer {
  .footer {
    position: absolute;
    bottom: 0;
    line-height: 60px;
    text-align: right;
    width: 100%;
    z-index: 99;
    background: white;
    padding-right: 20px;
    box-shadow: 0 2px 4px 0;
  }
}

.messagePool{
  text-align: center;
  color: white;
  margin: 0 10px;
  &>span{
  background: red;
  border-radius: 20px;
  color: white;
  padding: 3px 8px;
  font-size: 13px;
  }
}


::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 6px; /*高宽分别对应横竖滚动条的尺寸*/
  height: 15px;
}

::-webkit-scrollbar-thumb {
  /*滚动条里面小方块*/
  border-radius: 8px;
  -webkit-box-shadow: inset 0 0 5px #dcdfe6;
  box-shadow: inset 0 0 3px #dcdfe6;
  background: #dcdfe6;
}

::-webkit-scrollbar-track {
  /*滚动条里面轨道*/
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.2);
  border-radius: 10px;
  background: #ffffff;
}
</style>

